package com.atguigu.gulimall.member.interceptor;

import com.atguigu.gulimall.common.constant.AuthServerConstant;
import com.atguigu.gulimall.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @version 1.0
 * @author: YangDongDong
 * @date: 2025/4/19 上午10:14
 * @description: todo
 */

@Component
public class LoginUserInterceptor implements HandlerInterceptor
{
    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match)
        {
            return true;
        }


        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.SESSION_LOGIN_KEY);

        if (attribute != null)
        {
            loginUser.set(attribute);
            return true;
        }
        else
        {
            //提示语
            request.getSession().setAttribute("msg", "请先登录");
            //重定向到登录页
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
